import {
  CopilotRuntime,
  copilotRuntimeNextJSAppRouterEndpoint,
} from "@copilotkit/runtime";
import { NextRequest } from "next/server";

// 创建自定义适配器，连接到我们的Python后端
const customServiceAdapter = {
  async callRemoteAction(actionName: string, args: any) {
    // 这里会调用我们的Python后端
    const response = await fetch("http://localhost:8000/copilotkit", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        action: actionName,
        args: args,
      }),
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return await response.json();
  },
};

// 创建运行时，连接到我们的Python后端
const runtime = new CopilotRuntime({
  remoteActions: [
    {
      url: "http://localhost:8000/copilotkit",
    },
  ],
});

export const POST = async (req: NextRequest) => {
  const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
    runtime,
    serviceAdapter: customServiceAdapter,
    endpoint: "/api/copilotkit",
  });

  return handleRequest(req);
};
